/**
 * 
 */
package com.android.gtdroid;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

/**
 * @author xlees
 * 
 */
public class NewTaskAct extends Activity implements OnClickListener {
	private final String TAG = "NewTaskAct";
	public static final int RESULT_TAG = 2;
	public static final int RESULT_REMIND = 4;
	private final int DATE_DIALOG = 1;  
    private final int TIME_DIALOG = 2;
    private final int DLG_REMIND_TIME = 3;
    private final int DLG_REMIND = 4;

	private GTDApp ga;
	private int contextPos = 0;
	private int projectPos = 0;
	private int positionPos = 0;
	private ArrayList<Integer> alTag = new ArrayList<Integer>();
	private OnClickListener myDateListener;
	private OnClickListener myTimeListener;
	private TextView currentView;
	private int repeatId = R.id.tv_no_repeat;
	private String untilDate;
	private String remindTime;
	private int priorPos = 0;		// no priority
	private int listIndex = 0;		// inbox default
	private boolean agendaAdded;
	private View layout;
	private boolean isEdit;	// edit task or create a new task
	private HashMap<String, Object> hm;
	
	
	private Calendar calStart;
	private Calendar calEnd;
	private Calendar calCur;

	private EditText et_task;
	private EditText et_note;
	private LinearLayout ll_list;
	private LinearLayout ll_repeat;
	private LinearLayout ll_remind;
	private LinearLayout ll_prior;
	private TextView start_date, start_time;
	private TextView end_date, end_time;
	public String preTextStr;
	private CheckBox cb_day;
	private int taskStatus;
	

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		Log.i(TAG, "now onCreate method is called!");

		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.new_task);
		getWindow()
				.setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.tb_task);
		
		ga = (GTDApp) getApplication();
		calStart = Calendar.getInstance();
		calEnd = Calendar.getInstance();
		calCur = Calendar.getInstance();		// set to be the current date and time
		
		layout = ((LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE))
				.inflate(R.layout.agenda_added, null);
		
		taskStatus = getIntent().getIntExtra("task_status", C.TASK.UNCOMPLETED);
		listIndex = getIntent().getIntExtra("list_index", 0);
		if (listIndex == GTDApp.AGENDA) {
			LinearLayout sv = (LinearLayout) findViewById(R.id.ll_in_scroll);
	        LinearLayout ll_agd = (LinearLayout) layout.findViewById(R.id.ll_agd);
	        sv.addView(ll_agd, 2);
	        
	        agendaAdded = true;
		}
		
		et_task = (EditText) findViewById(R.id.et_task);
		et_task.clearFocus();
		et_note = (EditText) findViewById(R.id.et_note);
		ll_list = (LinearLayout) findViewById(R.id.ll_list);
		((TextView) findViewById(R.id.tv_list)).setText(ga.getListItems().get(listIndex).getListName());
		
		ll_remind = (LinearLayout) findViewById(R.id.ll_remind);
		ll_prior = (LinearLayout) findViewById(R.id.ll_prior);
		((TextView) findViewById(R.id.tv_prior)).setText(getString(R.string.prior_none));
		
		myDateListener = new ViewClickListener(DATE_DIALOG);
		myTimeListener = new ViewClickListener(TIME_DIALOG);

		if (ga == null)
			Log.i(TAG, "ga is null!");
		else
			Log.i(TAG, "ga is not null!");

		hm = (HashMap<String, Object>) getIntent().getSerializableExtra("task_data");
		if (hm != null) {		// edit task
			((TextView) findViewById(R.id.tv_task_title))
					.setText(getString(R.string.edit_task_title));
			if (((String) hm.get("item_list")).equals(getString(R.string.agenda))) {
				initAgenda();
//				agendaAdded = true;
			}
			isEdit = true;
			fillTaskData(hm);
			
			((Button) findViewById(R.id.btn_save_task)).setEnabled(true);
		} else {		// new task
			if (agendaAdded)
				initAgenda();
		}
		
		handleEvent();

	}
	
	// fill previous task data into each view if there is task data
	private void fillTaskData(HashMap<String, Object> hm) {
		et_task.setText((String) hm.get("item_name"));
		et_note.setText((String) hm.get("item_note"));
		((TextView) findViewById(R.id.tv_list)).setText((String) hm.get("item_list"));
		
		
		String context = (String) hm.get("item_context");
		if (context.equals(ga.getContexts().get(0)))	// no context
			((TextView) findViewById(R.id.tv_context)).setText("");
		else
			((TextView) findViewById(R.id.tv_context)).setText(context);
		
		String project = (String) hm.get("item_project");
		if (project.equals(ga.getProjects().get(0)))
			((TextView) findViewById(R.id.tv_project)).setText("");
		else
			((TextView) findViewById(R.id.tv_project)).setText(project);
		
		String pos = (String) hm.get("item_pos");
		if (pos.equals(ga.getPositions().get(0)))
			((TextView) findViewById(R.id.tv_position)).setText("");
		else
			((TextView) findViewById(R.id.tv_position)).setText(pos);
		
		if (((String) hm.get("item_list")).equals(getString(R.string.agenda))) {	// this is an agenda
			String date, time;
			String[] tmp;
			String start = (String) hm.get("item_st");
			String end = (String) hm.get("item_et");
			
			((Button) findViewById(R.id.btn_save_task)).setEnabled(true);
			
			int status = (Integer) hm.get("item_status");
			if (status == 1)
				cb_day.setChecked(true);
			else
				cb_day.setChecked(false);
			
			if (start.length() > 1) {
				tmp = start.split(" ");
				date = tmp[0];
				if (tmp.length > 1) { // date and time
					time = tmp[1];
				} else {	// only the date
					time = "";
				}
				start_date.setText(date);
				start_time.setText(time);
			} else {
				start_date.setText("");
				start_time.setText("");
			}
			
			if (end.length() > 1) {
				tmp = end.split(" ");
				date = tmp[0];
				if (tmp.length > 1)
					time = tmp[1];
				else
					time = "";
				end_date.setText(date);
				end_time.setText(time);
			} else {
				end_date.setText("");
				end_time.setText("");
			}
			
			((TextView) findViewById(R.id.tv_repeat)).setText((String) hm.get("item_repeat"));
		}
		
		((TextView) findViewById(R.id.tv_remind)).setText((String) hm.get("item_remind"));
		((TextView) findViewById(R.id.tv_prior)).setText((String) hm.get("item_prior"));
		((TextView) findViewById(R.id.tv_tag)).setText((String) hm.get("item_tags"));
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		
		Log.i(TAG, "now onStart method is called!");
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Log.i(TAG, "now onResume method is called!");
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		Log.i(TAG, "now onStop method is called!");

		// savePreferences();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		// ga.close();
		Log.i(TAG, "now onDestroy method is called!");
		super.onDestroy();
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		Log.i(TAG, "now restart method is called!");
	}

	
	

	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		// return super.onCreateDialog(id);
		Log.e(TAG, "onCreateDialog is called!!");
		
		Dialog dlg = null;
		switch (id) {
			case DATE_DIALOG:
				OnDateSetListener dateListener = new OnDateSetListener() {
					@Override
					public void onDateSet(DatePicker datePicker, int year,
							int month, int dayOfMonth) {
						/******* Calendars have milliseconds, must clear it *****/
						calStart.clear(Calendar.MILLISECOND);
						calCur.clear(Calendar.MILLISECOND);
						
						int viewId = currentView.getId();
						switch (viewId) {
							case R.id.start_date:
								calStart.set(Calendar.YEAR, year);
								calStart.set(Calendar.MONTH, month);
								calStart.set(Calendar.DAY_OF_MONTH, dayOfMonth);
								
								Log.e(TAG, "current date: "+calCur.get(Calendar.YEAR)
										+ " "+calCur.get(Calendar.MONTH)
										+ " "+calCur.get(Calendar.DAY_OF_MONTH));
								Log.e(TAG, "start date: "+calStart.get(Calendar.YEAR)
										+ " "+calStart.get(Calendar.MONTH)
										+ " "+calStart.get(Calendar.DAY_OF_MONTH));
								
								if (calStart.before(calCur) || calStart.after(calEnd)) {
									Log.e(TAG, "start date is before current date!");
									
									Toast.makeText(NewTaskAct.this, "��ǰ�����ѹ���", Toast.LENGTH_LONG).show();
									currentView.setText(preTextStr);
									
									showDialog(DATE_DIALOG);
								} /*else if (calStart.after(calCur)) {
									Log.e(TAG, "start date is after current date!");
									
									currentView.setText(year
											+ "-" + format2((month+1))
											+ "-" + format2(dayOfMonth));
								}*/ else {
									Log.e(TAG, "start date is equal or after current date!");
									
									currentView.setText(year
											+ "-" + format2((month+1))
											+ "-" + format2(dayOfMonth));
								}
								break;
								
							case R.id.end_date:
								calEnd.set(Calendar.YEAR, year);
								calEnd.set(Calendar.MONTH, month);
								calEnd.set(Calendar.DAY_OF_MONTH, dayOfMonth);
								
								if (calEnd.after(calStart) || calEnd.equals(calStart)) {
									currentView.setText(year
											+ "-" + format2((month+1))
											+ "-" + format2(dayOfMonth));
								} else {
									Toast.makeText(NewTaskAct.this,"��ǰ�����ѹ���", Toast.LENGTH_LONG).show();
									currentView.setText(preTextStr);
									
									showDialog(DATE_DIALOG);
								}
								break;
								
							default:
								break;
						}
					}
				};
				
				dlg = new DatePickerDialog(this, dateListener, 1111, 10, 11);
				break;
				
			case TIME_DIALOG:
				OnTimeSetListener timeListener = new OnTimeSetListener() {
					@Override
					public void onTimeSet(TimePicker timerPicker, int hourOfDay,
							int minute) {
						/******* Calendars have milliseconds, must clear it *****/
						calStart.clear(Calendar.MILLISECOND);
						calCur.clear(Calendar.MILLISECOND);
						calEnd.clear(Calendar.MILLISECOND);
						
						/*int curYear = calendar.get(Calendar.YEAR);
						int curMonth = calendar.get(Calendar.MONTH)+1;
						int curDay = calendar.get(Calendar.DAY_OF_MONTH);
						int curHour = calendar.get(Calendar.HOUR_OF_DAY);
						int curMinute = calendar.get(Calendar.MINUTE);*/
						
						int viewId = currentView.getId();
						switch (viewId) {
							case R.id.start_time:
								calStart.set(Calendar.HOUR_OF_DAY, hourOfDay);
								calStart.set(Calendar.MINUTE, minute);
								
								Log.e(TAG, "End time: "+calEnd.get(Calendar.YEAR)
										+ " "+calEnd.get(Calendar.MONTH)
										+ " "+calEnd.get(Calendar.DAY_OF_MONTH)
										+ " "+calEnd.get(Calendar.HOUR_OF_DAY)
										+ " "+calEnd.get(Calendar.MINUTE));
								Log.e(TAG, "start time: "+calStart.get(Calendar.YEAR)
										+ " "+calStart.get(Calendar.MONTH)
										+ " "+calStart.get(Calendar.DAY_OF_MONTH)
										+ " "+hourOfDay
										+ " "+minute);
								
								if (calStart.before(calCur) || calStart.after(calEnd)) {
									Toast.makeText(NewTaskAct.this,"��ǰʱ���ѹ���", Toast.LENGTH_LONG).show();
									showDialog(TIME_DIALOG);
								} else {
									currentView.setText(format2(hourOfDay) + ":" + format2(minute));
								}
								break;
								
							case R.id.end_time:
								calEnd.set(Calendar.HOUR_OF_DAY, hourOfDay);
								calEnd.set(Calendar.MINUTE, minute);
								
								if (calEnd.before(calStart)) {
									Toast.makeText(NewTaskAct.this,"��ǰʱ���ѹ���", Toast.LENGTH_LONG).show();
									showDialog(TIME_DIALOG);
								} else {
									currentView.setText(format2(hourOfDay) + ":" + format2(minute));
								}
								break;
								
							default:
								break;
						}
					}
				};
				
				/*String strTime = currentView.getText().toString().trim();
				String[] arrayTime = strTime.split(":");
				int hour = Integer.valueOf(arrayTime[0]);
				int minute = Integer.valueOf(arrayTime[1]);*/
				
				dlg = new TimePickerDialog(this, timeListener, 11, 11, true); // �Ƿ�Ϊ��ʮ����
				break;
				
			case DLG_REMIND_TIME:		// all day remind dialog
				dlg = new Dialog(this);
				dlg.setContentView(R.layout.date_time);
				dlg.setTitle("��������ʱ��");
				
				LinearLayout ll_remind_date = (LinearLayout) dlg.findViewById(R.id.ll_remind_date);
				ll_remind_date.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						showDialog(DATE_DIALOG);
					}
				});
				break;
				
			case DLG_REMIND:
				break;
				
			default:
				break;
		}

		return dlg;
	}
	
	@Override
	protected void onPrepareDialog(int id, final Dialog dialog) {
		// TODO Auto-generated method stub
//		super.onPrepareDialog(id, dialog);
		Log.i(TAG, "onPrepareDialog is called!");
		
		String strDate, strTime;
		String[] arrayDate, arrayTime;
		
		switch (id) {
			case DATE_DIALOG:
				/*int viewId = currentView.getId();
				switch(viewId) {
				case R.id.start_date:
					break;
				case R.id.end_date:
					break;
				default:
					break;
				}*/
				strDate = currentView.getText().toString().trim();
				if (strDate.length() > 0) {
					arrayDate = strDate.split("-");
					int year = Integer.valueOf(arrayDate[0]);
					int month = Integer.valueOf(arrayDate[1]);
					int day = Integer.valueOf(arrayDate[2]);
					((DatePickerDialog) dialog).updateDate(year, month-1, day);
				} else {
					((DatePickerDialog) dialog).updateDate(calCur.get(Calendar.YEAR),
							calCur.get(Calendar.MONTH),
							calCur.get(Calendar.DAY_OF_MONTH));
				}
				break;
				
			case TIME_DIALOG:
				strTime = currentView.getText().toString().trim();
				if (strTime.length() > 0) {
					arrayTime = strTime.split(":");
					int hour = Integer.valueOf(arrayTime[0]);
					int minute = Integer.valueOf(arrayTime[1]);
					((TimePickerDialog) dialog).updateTime(hour, minute);
				} else {
//					calEnd.setTime(date)
				}
				break;
				
			case DLG_REMIND_TIME:
				String str = ((TextView) findViewById(R.id.tv_remind)).getText().toString().trim();
				if (str.length() > 0) {
					String[] dateTime = str.split(" ");
					((TextView) findViewById(R.id.tv_remind_date)).setText(dateTime[0]);
					((TextView) findViewById(R.id.tv_remind_time)).setText(dateTime[1]);
				}
				
				Button btn_remind_cal = (Button) dialog.findViewById(R.id.btn_remind_cal);
				btn_remind_cal.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						dialog.cancel();
					}
				});
				break;
				
			default:
				break;
		}
	}
	
	private String format2(int x) {
		String s = "" + x;
		if (s.length() == 1)
			s = "0" + s;
		
		return s;
	}
	
	private void initAgenda() {
		cb_day = (CheckBox) layout.findViewById(R.id.cb_day);
		start_date = (TextView) layout.findViewById(R.id.start_date);
		start_time = (TextView) layout.findViewById(R.id.start_time);
		end_date = (TextView) layout.findViewById(R.id.end_date);
		end_time = (TextView) layout.findViewById(R.id.end_time);
		ll_repeat = (LinearLayout) layout.findViewById(R.id.ll_repeat);
		
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm");
		
		// all day
		cb_day.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				// TODO Auto-generated method stub
				SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
				SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm");
				
				if (isChecked) {
					start_date.setText(sdf1.format(calCur.getTime()));
					start_time.setText("");
					end_date.setText(sdf1.format(calCur.getTime()));
					end_time.setText("");
					
					start_time.setOnClickListener(null);
					end_time.setOnClickListener(null);
				} else {
					int minute = calCur.get(Calendar.MINUTE);
					
					if (minute>=0 && minute<30)
						calStart.set(Calendar.MINUTE, 30);
					if (minute>=30 && minute<=59) {
						calStart.add(Calendar.MINUTE, 60-minute);
//						calStart.add(Calendar.HOUR_OF_DAY, 1);
					}
					
					start_date.setText(sdf1.format(calStart.getTime()));
					start_time.setText(sdf2.format(calStart.getTime()));
					end_date.setText("");
					end_time.setText("");
					
					start_time.setOnClickListener(myTimeListener);
					end_time.setOnClickListener(myTimeListener);
				}
				
				((TextView) findViewById(R.id.tv_remind)).setText("");
			}
		});
		
		// start time and end time
		if (cb_day.isChecked())	{	// all day task
			start_date.setText(sdf1.format(calCur.getTime()));
			start_time.setText("");	
			
			end_date.setText(sdf1.format(calCur.getTime()));
			end_time.setText("");
			
			start_date.setOnClickListener(myDateListener);
			end_date.setOnClickListener(myDateListener);
		} else {		// specific time task
			int minute = calCur.get(Calendar.MINUTE);
			
			if (minute>=0 && minute<30)
				calStart.set(Calendar.MINUTE, 30);
			if (minute>=30 && minute<=59) {
				calStart.add(Calendar.MINUTE, 60-minute);
//				calStart.add(Calendar.HOUR_OF_DAY, 1);
			}
			
			start_date.setText(sdf1.format(calStart.getTime()));
			start_time.setText(sdf2.format(calStart.getTime()));
			
			// default: end time is null
			end_date.setText("");
			end_time.setText("");
			
			start_date.setOnClickListener(myDateListener);
			start_time.setOnClickListener(myTimeListener);
			end_date.setOnClickListener(myDateListener);
			end_time.setOnClickListener(myTimeListener);
		}
		
		// repeat event
		((TextView) layout.findViewById(R.id.tv_repeat)).setText("");
		ll_repeat.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent itt = new Intent(NewTaskAct.this, RepeatAct.class);
				Bundle bd = new Bundle();
				
				bd.putInt("repeat_id", repeatId);
				if (repeatId == R.id.ll_until)
					bd.putString("until_date", untilDate);
				itt.putExtras(bd);
				startActivityForResult(itt, 0);
			}
		});
	}

	private void handleEvent() {
		ll_list.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				ArrayList<String> als = new ArrayList<String>();
				ArrayList<ListItem> al = ga.getListItems();
				
				for (int i=0; i<al.size(); i++)
					als.add(al.get(i).getListName());
				final String[] items = (String[]) als.toArray(new String[als.size()]);
				
				AlertDialog.Builder builder = new AlertDialog.Builder(NewTaskAct.this);
				builder.setTitle("��ѡ�������嵥");
				builder.setSingleChoiceItems(items, listIndex, new DialogInterface.OnClickListener() {
				    public void onClick(DialogInterface dialog, int item) {
				    	String str = items[item];
				    	listIndex = item;
				    	((TextView) findViewById(R.id.tv_list)).setText(str);
				    	
				    	if (item == GTDApp.AGENDA) {
				    		LinearLayout sv = (LinearLayout) findViewById(R.id.ll_in_scroll);
//				    		LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
//				            View layout = inflater.inflate(R.layout.agenda_added, null);
				            LinearLayout ll_agd = (LinearLayout) layout.findViewById(R.id.ll_agd);
				    		
				    		if (!agendaAdded) {
					            sv.addView(ll_agd, 2);
					            
					            initAgenda();
					            
					            agendaAdded = true;
				    		}
				    	} else {
				    		if (agendaAdded) {
				    			LinearLayout toRemoved = ((LinearLayout) layout.findViewById(R.id.ll_agd));
					    		if (toRemoved != null) {
						    		ViewGroup vg = (ViewGroup) toRemoved.getParent();
						    		vg.removeView(toRemoved);
						    		agendaAdded = false;
					    		}
				    		}
				    	}
				    	
				    	dialog.dismiss();
				    }
				});
				builder.show();
			}
		});
		
		ll_prior.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				final String[] items = (String[]) ga.prior.toArray(new String[ga.prior.size()]);
				
				AlertDialog.Builder builder = new AlertDialog.Builder(NewTaskAct.this);
				builder.setTitle(getString(R.string.prior_title));
				builder.setSingleChoiceItems(items, priorPos, new DialogInterface.OnClickListener() {
				    public void onClick(DialogInterface dialog, int item) {
//				        Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
				    	String str = items[item];
				    	priorPos = item;
				    	((TextView) findViewById(R.id.tv_prior)).setText(str);
				    	dialog.dismiss();
				    }
				});
				builder.show();
			}
		});
		
		/**
		 * Save a task
		 */
		final Button btn_save_task = (Button) findViewById(R.id.btn_save_task);
		btn_save_task.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String new_task, task_note, task_list;
				String task_ctt = "", task_prj = "", task_pos = "";
				String stDate="", stTime="", etDate="", etTime="", repeat="";
				String remind, strPrior, tag;

				// first group
				new_task = et_task.getText().toString();
				task_note = et_note.getText().toString();
				task_list = ((TextView) findViewById(R.id.tv_list)).getText().toString();

				// second group
				task_ctt = ((TextView) findViewById(R.id.tv_context)).getText().toString();
				if (task_ctt.length() == 0)
					task_ctt = ga.getContexts().get(0);
				task_prj = ((TextView) findViewById(R.id.tv_project)).getText().toString();
				if (task_prj.length() == 0)
					task_prj = ga.getProjects().get(0);
				task_pos = ((TextView) findViewById(R.id.tv_position)).getText().toString();
				if (task_pos.length() == 0)
					task_pos = ga.getPositions().get(0);

				// third group (=== remember to verify the date and time of the task =====)
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date curTime = calCur.getTime();
				Date startDate = calStart.getTime();
				
				if (agendaAdded) {
					stDate = start_date.getText().toString();
					etDate = end_date.getText().toString();
					
					calStart.clear(Calendar.MILLISECOND);
					calEnd.clear(Calendar.MILLISECOND);
					calCur.clear(Calendar.MILLISECOND);
					
					if (cb_day.isChecked()) {		// all day task
						stTime = new String("00:00");
						etTime = new String("23:59");
						
						Log.e("current time", calCur.get(Calendar.HOUR_OF_DAY)+" "+calCur.get(Calendar.DAY_OF_MONTH));
						Log.e("start time", calStart.get(Calendar.HOUR_OF_DAY)+" "+calStart.get(Calendar.DAY_OF_MONTH));
						
						// check start date
						try {
							startDate = (new SimpleDateFormat("yyyy-MM-dd")).parse(stDate);		// 00:00
						} catch (ParseException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
						calStart.setTime(startDate);
						calStart.set(Calendar.HOUR_OF_DAY, calCur.get(Calendar.HOUR_OF_DAY));
						calStart.set(Calendar.MINUTE, calCur.get(Calendar.MINUTE));
						calStart.set(Calendar.SECOND, calCur.get(Calendar.SECOND));		// must add
						
						if (calStart.before(calCur)) {
							Toast.makeText(NewTaskAct.this, "��ǰ��ʼ�����ѹ��ڣ�����������", Toast.LENGTH_LONG).show();
							/*Toast.makeText(NewTaskAct.this,
									"current: "+calCur.get(Calendar.YEAR)
									+"-"+calCur.get(Calendar.MONTH)
									+"-"+calCur.get(Calendar.DAY_OF_MONTH)
									+" "+calCur.get(Calendar.HOUR_OF_DAY)
									+":"+calCur.get(Calendar.MINUTE)
									+":"+calCur.get(Calendar.SECOND)
									+"  start: "+calStart.get(Calendar.YEAR)
									+"-"+calStart.get(Calendar.MONTH)
									+"-"+calStart.get(Calendar.DAY_OF_MONTH)
									+" "+calStart.get(Calendar.HOUR_OF_DAY)
									+":"+calStart.get(Calendar.MINUTE)
									+":"+calStart.get(Calendar.MINUTE),
									Toast.LENGTH_LONG).show();*/
							return;
						}
					} else {	// time-specific task
						stTime = start_time.getText().toString();
						etTime = end_time.getText().toString();
						
						// get strings of start time and end time
						try {
							startDate = sdf.parse(stDate+" "+stTime);
						} catch (ParseException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
						calStart.setTime(startDate);
						calStart.set(Calendar.SECOND, calCur.get(Calendar.SECOND));
						
						if (calStart.before(calCur)) {
							Toast.makeText(NewTaskAct.this, "��ǰ��ʼ�����ѹ��ڣ�����������", Toast.LENGTH_LONG).show();
							/*Toast.makeText(NewTaskAct.this,
									calCur.get(Calendar.YEAR)+"-"+calCur.get(Calendar.MONTH)+"-"
									+calCur.get(Calendar.DAY_OF_MONTH)+" "+calCur.get(Calendar.HOUR_OF_DAY)
									+":"+calCur.get(Calendar.MINUTE),
									Toast.LENGTH_LONG).show();*/
							
							return;
						}
					}
					
					// repeat
					repeat = ((TextView) findViewById(R.id.tv_repeat)).getText().toString();
					
					Log.e(TAG, "repeat string: "+ repeat);
					
					if (repeatId == R.id.ll_until) {		// need to 	verify data
						Calendar calUntil = Calendar.getInstance();
						Date until = calCur.getTime();
						try {
							until = sdf1.parse((repeat.split(" "))[1]
									+ " " +"23:59:59");
						} catch (ParseException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						calUntil.setTime(until);
						
						if (calUntil.before(calCur)) {
							Toast.makeText(NewTaskAct.this, "�ظ������ѹ��ڣ�����������", Toast.LENGTH_LONG).show();
							/*((TextView) findViewById(R.id.tv_repeat)).setText(
									curTime.getHours()+":"+curTime.getMinutes());*/
							return;
						}
					}
				}	// end agendaAdded
				
				// remind
				remind = ((TextView) findViewById(R.id.tv_remind)).getText().toString();
				if (!agendaAdded || cb_day.isChecked()) {		// all day task
					if (remind.length() > 0) {
						Calendar cld = Calendar.getInstance();
						Date remindTime = cld.getTime();
						try {
							remindTime = sdf1.parse(remind+":00");
						} catch (ParseException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						cld.setTime(remindTime);
						
						if (cld.before(calCur)) {
							Toast.makeText(NewTaskAct.this, "���������ѹ��ڣ�����������", Toast.LENGTH_LONG).show();
							((TextView) findViewById(R.id.tv_remind)).setText(sdf.format(curTime));
							return;
						}
					}
				}
				
				// fourth grouop
				strPrior = ((TextView) findViewById(R.id.tv_prior)).getText().toString();
				tag = ((TextView) findViewById(R.id.tv_tag)).getText().toString();		// String array
				
				
				// Insert a new task item into database
				TaskItem taskItem = new TaskItem(new_task, task_note, task_list);

				taskItem.setContext(task_ctt);
				taskItem.setProject(task_prj);
				taskItem.setPosition(task_pos);
				
				if (agendaAdded) {
					taskItem.setAllDay(cb_day.isChecked());
					taskItem.setStartTime(stDate+" "+stTime);
					taskItem.setEndTime(etDate+" "+etTime);
					taskItem.setRepeat(repeat);
				} else {
					taskItem.setAllDay(true);		// no agenda, default all day
					taskItem.setStartTime(null);
					taskItem.setEndTime(null);
					taskItem.setRepeat(null);
				}
				taskItem.setRemind(remind);
				
				/*if (strPrior.equals("��"))
					taskItem.setPrior(TaskItem.NONE);
				else if (strPrior.equals("��"))
					taskItem.setPrior(TaskItem.HIGH);
				else if (strPrior.equals("��"))
					taskItem.setPrior(TaskItem.MEDIUM);
				else if (strPrior.equals("��"))
					taskItem.setPrior(TaskItem.LOW);
				else
					;*/
				taskItem.setPrior(strPrior);
				
				taskItem.setTags(tag);		// string array split by ","
				
				taskItem.setCompletedStatus(C.TASK.UNCOMPLETED);
				String tmp = sdf.format(curTime);
				taskItem.setCreated(tmp);
				
				/*Log.e("NEW TASK", new_task+" "+task_note+" "+task_list
						+" "+task_ctt+" "+task_prj+" "+task_pos
						+" "+cb_day.isChecked()+" "+stDate+" "+stTime
						+" "+etDate+" "+etTime+" "
						+repeat+" "+remind+" "+prior+" "+tag+" "+sdf.format(curTime));*/
				
				if (isEdit)
					ga.getDbta().updateTask((Long) hm.get("item_id"), taskItem);
				else
					ga.getDbta().insertTask(taskItem);
				ga.updateTask();

				Intent itt = new Intent();
				setResult(RESULT_OK, itt);
				finish();
			}
		});

		OnClickListener ocl = new Button.OnClickListener() {
			public void onClick(View v) {
				Intent itt = new Intent();
				setResult(0, itt);
				finish();
			}
		};
		Button btn_cal_task = (Button) findViewById(R.id.btn_cal_task);
		btn_cal_task.setOnClickListener(ocl);
		Button btn_return = (Button) findViewById(R.id.btn_return);
		btn_return.setOnClickListener(ocl);

		EditText et_title = (EditText) findViewById(R.id.et_task);
		et_title.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				if (s.length() > 0)
					btn_save_task.setEnabled(true);
				else
					btn_save_task.setEnabled(false);
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				
			}
		});
		
		/*OnClickListener ll_ocl = new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				int code;
				Intent itt;
				LinearLayout llv = (LinearLayout) v;

				String str = ((TextView) llv.getChildAt(0)).getText()
						.toString();
				Bundle bd = new Bundle();
				
				if (str.equals(context)) {
					code = 0;
					bd.putInt("pos", contextPos);
				}
				else if (str.equals(project)) {
					code = 1;
					bd.putInt("pos", projectPos);
				}
				else if (str.equals(position)) {
					code = 2;
					bd.putInt("pos", positionPos);
				}
				else if (str.equals(tag))
					code = 3;
				else
					code = -1;
				
				bd.putInt("view_code", code);
				bd.putString("view_name", str);
				
				if (code == 3) {
					itt = new Intent(NewTaskAct.this, TagAct.class);
					bd.putInt("tag_count", alTag.size());
					bd.putIntegerArrayList("selected", alTag);
					
					 * for (int i = 0; i < alTag.size(); i++) {
					 * bd.putInt("selected[" + i + "]", alTag.get(i)); }
					 

				} else {
					itt = new Intent(NewTaskAct.this, ViewAct.class);
				}
				
				if (str.equals(""))
					Log.e(TAG, "got an empty string!");

				itt.putExtras(bd);
				startActivityForResult(itt, 0);
			}
		};*/

		((LinearLayout) findViewById(R.id.ll_context)).setTag(C.TASK.CONTEXT);
		((LinearLayout) findViewById(R.id.ll_project)).setTag(C.TASK.PROJECT);
		((LinearLayout) findViewById(R.id.ll_position)).setTag(C.TASK.POSITION);
		((LinearLayout) findViewById(R.id.ll_tag)).setTag(C.TASK.TAG);
		
		((LinearLayout) findViewById(R.id.ll_context))
				.setOnClickListener(this);
		((LinearLayout) findViewById(R.id.ll_project))
				.setOnClickListener(this);
		((LinearLayout) findViewById(R.id.ll_position))
				.setOnClickListener(this);
		((LinearLayout) findViewById(R.id.ll_tag)).setOnClickListener(this);
		
		// remind event
		ll_remind.setTag(C.TASK.REMIND);
		ll_remind.setOnClickListener(this);
		
		
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent itt = null;
		Bundle bd = new Bundle();
		int tag = (Integer) v.getTag();
		
		switch (tag) {
			case C.TASK.CONTEXT:
				bd.putInt("pos", contextPos);
				bd.putInt("view_code", C.TASK.CONTEXT);
				bd.putString("view_name", getString(R.string.context));
				
				itt = new Intent(NewTaskAct.this, ViewAct.class);
				
				break;
				
			case C.TASK.PROJECT:
				bd.putInt("pos", projectPos);
				bd.putInt("view_code", C.TASK.PROJECT);
				bd.putString("view_name", getString(R.string.project));
				
				itt = new Intent(NewTaskAct.this, ViewAct.class);
				
				break;
				
			case C.TASK.POSITION:
				bd.putInt("pos", positionPos);
				bd.putInt("view_code", C.TASK.POSITION);
				bd.putString("view_name", getString(R.string.position));
				
				itt = new Intent(NewTaskAct.this, ViewAct.class);
				
				break;
				
			case C.TASK.REMIND:
				if (agendaAdded
						&& !((CheckBox) findViewById(R.id.cb_day)).isChecked()) {	// all day task
					AlertDialog.Builder builder = new AlertDialog.Builder(NewTaskAct.this);
					builder.setTitle(getString(R.string.remind_title));
					final String[] items = (String[]) ga.remind.toArray(new String[ga.remind.size()]);
					builder.setSingleChoiceItems(items, listIndex, new DialogInterface.OnClickListener() {
					    public void onClick(DialogInterface dialog, int item) {
//					        Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
					    	String str = items[item];
					    	((TextView) findViewById(R.id.tv_remind)).setText(str);
					    	dialog.dismiss();
					    }
					});
					builder.show();
				}
				else {
					itt = new Intent(NewTaskAct.this, RemindAct.class);
					bd = new Bundle();
					
					remindTime = ((TextView) findViewById(R.id.tv_remind)).getText().toString();
					bd.putString("time", remindTime);
					itt.putExtras(bd);
					startActivityForResult(itt, 0);
				}
				
				return;
				
			case C.TASK.TAG:
				bd.putInt("tag_count", alTag.size());
				bd.putIntegerArrayList("selected", alTag);
				bd.putInt("view_code", C.TASK.TAG);
				bd.putString("view_name", getString(R.string.tag));
				
				itt = new Intent(NewTaskAct.this, TagAct.class);
				
				break;
				
			default:
				break;
		}
		
		itt.putExtras(bd);
		startActivityForResult(itt, 0);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		Bundle bd = null;
		
		Log.i(TAG, "onActivityResult method is called!");

		if (data != null)
			bd = data.getExtras();
		switch (resultCode) {
		case RESULT_OK:
			String str = bd.getString("selected");
			int viewCode = bd.getInt("code");

			switch (viewCode) {
			case C.TASK.CONTEXT: // context
				contextPos = bd.getInt("pos");
				if (contextPos > 0)
					((TextView) findViewById(R.id.tv_context)).setText(str);
				break;
				
			case C.TASK.PROJECT: // project
				projectPos = bd.getInt("pos");
				if (projectPos > 0)
					((TextView) findViewById(R.id.tv_project)).setText(str);
				break;
				
			case C.TASK.POSITION: // position
				positionPos = bd.getInt("pos");
				if (positionPos > 0)
					((TextView) findViewById(R.id.tv_position)).setText(str);
				break;
				
			default:
				break;
			}
			break;
			
		case RESULT_CANCELED: // press back button
			Log.i(TAG, "you return here!");
			break;
			
		case RESULT_TAG:
			Bundle bd1 = data.getExtras();
			int size = bd1.getInt("tag_count");
			alTag.clear();
			alTag = bd1.getIntegerArrayList("selected");
			/*
			 * for (int i = 0; i < size; i++) alTag.add(bd1.getInt("selected[" +
			 * i + "]"));
			 */
			if (size > 0) {
				String rst = "";
				if (size >= 2) {
					for (int i = 0; i < size - 1; i++)
						rst += ga.getTags().get(alTag.get(i).intValue()) + ", ";
				}
				rst += ga.getTags().get(alTag.get(size - 1).intValue());
				((TextView) findViewById(R.id.tv_tag)).setText(rst);
			}
			break;
			
		case RepeatAct.RESULT_REPEAT:
			int type = bd.getInt("repeat");
			repeatId = bd.getInt("repeat_id");
			if (type == 3) {		// workday
				String tmp = ga.repeat.get(type)+"����һ�����壩";
				((TextView) findViewById(R.id.tv_repeat)).setText(tmp);
			}
			else if (type == 6) {
				untilDate = bd.getString("until_date");
				((TextView) findViewById(R.id.tv_repeat)).setText(ga.repeat.get(type)+" "+untilDate);
			}
			else
				((TextView) findViewById(R.id.tv_repeat)).setText(ga.repeat.get(type));
			break;
			
		case RESULT_REMIND:
			str = bd.getString("time");
			remindTime = str;
			((TextView) findViewById(R.id.tv_remind)).setText(str);
			break;
		default:
			break;
		}
	}

	/*
	 * private class for onClickListener interface
	 * 
	 */
	private class ViewClickListener implements OnClickListener {

		private int dialogId = 0; //

		public ViewClickListener(int dialogId) {
			this.dialogId = dialogId;
		}
		
		@Override
		public void onClick(View view) {
			int viewId = view.getId();
			currentView = (TextView) view;
			
			switch (viewId) {
				case R.id.start_date:
				case R.id.start_time:
				case R.id.end_date:
				case R.id.end_time:
					showDialog(dialogId);
					preTextStr = currentView.getText().toString();
					break;
					
				case R.id.tv_no_repeat:
					break;
					
				case R.id.tv_day:
					break;
				
				case R.id.tv_week:
					break;
					
				case R.id.tv_workday:
					break;
					
				case R.id.tv_month:
					break;
					
				case R.id.tv_year:
					break;
					
				case R.id.tv_until:
					break;
			}
		}
	}
}
